package com.common.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
public class DruidConfig {
    //将数据源加入到到配置文件中
    @Bean(name="dataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource(){
        return DruidDataSourceBuilder.create().build();
    }
    //配置后台监控
    @Bean
    public ServletRegistrationBean statViewServlet(){
        //配置后台访问路径
        ServletRegistrationBean<StatViewServlet> bean =new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
        HashMap<String,String> initParameters = new HashMap<>();
        //登录用户 注意是固定写法
        initParameters.put("loginUsername","lijiang");
        initParameters.put("loginPassword","d123456");
        //允许谁能访问
        //allow key为空则所有人可以访问 可以配置localhost ....
        initParameters.put("allow","");
        // 配置不可以访问对象 initParameters.put("name","ip");
        bean.setInitParameters(initParameters);
        return bean;
    }

//    //过滤
//    @Bean
//    public FilterRegistrationBean webStatFilter(){
//
//        FilterRegistrationBean bean = new FilterRegistrationBean();
//        //添加过滤请求
//        HashMap<String,String> initParameters = new HashMap<>();
//        //不进行统计的数据
//        initParameters.put("exclusions","*.js,*.css,/druid/*");
//        bean.setInitParameters(initParameters);
//        return bean;
//    }
@Bean
public FilterRegistrationBean statFilter(){
    //创建过滤器
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
    //设置过滤器过滤路径
    filterRegistrationBean.addUrlPatterns("/*");
    //忽略过滤的形式
    filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    return filterRegistrationBean;
}
}
